//
//  QSLoginViewController.m
//  DigitalEconomy_iOS
//
//  Created by Ding on 2020/3/17.
//  Copyright © 2020 DingC. All rights reserved.
//

#import "QSLoginViewController.h"
#import "JKCountDownButton.h"
#import "QSUserInterface.h"
@interface QSLoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UIImageView *backgroudImageView;
@property (nonatomic, strong)UIImageView *titleBackgroundImageView;
@property (nonatomic, strong)UIView *whiteBackgroundView;
@property (nonatomic, strong)UIImageView *phoneImageView;
@property (nonatomic, strong)UITextField *phoneTextField;
@property (nonatomic, strong)UIView *phoneLineView;
@property (nonatomic, strong)UIImageView *codeImageView;
@property (nonatomic, strong)UITextField *codeTextField;
@property (nonatomic, strong)UIView *codeLineView;
@property (nonatomic, strong)JKCountDownButton *sendCodeButton;
@property (nonatomic, strong)UIButton *loginButton;

@end

@implementation QSLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configSubView];
    self.backgroudImageView.userInteractionEnabled = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)configSubView{
    [self.view addSubview:self.backgroudImageView];
    [self.backgroudImageView addSubview:self.titleBackgroundImageView];
    [self.view addSubview:self.whiteBackgroundView];
    [self.whiteBackgroundView addSubview:self.phoneImageView];
    [self.whiteBackgroundView addSubview:self.phoneTextField];
    [self.whiteBackgroundView addSubview:self.phoneLineView];
    [self.whiteBackgroundView addSubview:self.codeImageView];
    [self.whiteBackgroundView addSubview:self.codeTextField];
    [self.whiteBackgroundView addSubview:self.codeLineView];
    [self.whiteBackgroundView addSubview:self.sendCodeButton];
    [self.whiteBackgroundView addSubview:self.loginButton];
    
    [_backgroudImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.width.equalTo(self.view);
        make.height.equalTo(_backgroudImageView.mas_width).multipliedBy(0.8);
    }];
    [_whiteBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(kRealValue(18));
        make.right.equalTo(self.view.mas_right).offset( -kRealValue(18));
        make.centerY.equalTo(self.view);
        make.height.equalTo(_whiteBackgroundView.mas_width).multipliedBy(1);
    }];
    
    [_titleBackgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_backgroudImageView).offset(kRealValue(32));
        make.right.equalTo(_backgroudImageView).offset(- kRealValue(32));
        make.bottom.equalTo(_whiteBackgroundView.mas_top).offset(- kRealValue(42));
//        make.height.offset(kRealValue(36));
    }];
    [_phoneImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_whiteBackgroundView).offset(kRealValue(19));
        make.top.equalTo(_whiteBackgroundView).offset(kRealValue(62));
        make.width.height.offset(kRealValue(23));
    }];
    
    [_phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_phoneImageView.mas_right).offset(kRealValue(19));
        make.right.equalTo(_whiteBackgroundView).offset(- kRealValue(10));
        make.centerY.equalTo(_phoneImageView);
        make.height.equalTo(_phoneImageView);
    }];
    [_phoneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneImageView.mas_bottom).offset(kRealValue(21));
        make.left.equalTo(_whiteBackgroundView).offset(kRealValue(19));
        make.right.equalTo(_whiteBackgroundView).offset(- kRealValue(19));
        make.height.offset(1);
    }];
    [_codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.height.equalTo(_phoneImageView);
        make.top.equalTo(_phoneLineView).offset(kRealValue(23));
    }];
    [_sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_codeImageView);
        make.right.equalTo(_whiteBackgroundView).offset(- kRealValue(19));
        make.width.offset(kRealValue(50));
        make.height.offset(kRealValue(30));
    }];
    [_codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_sendCodeButton.mas_left).offset(- kRealValue(5));
        make.left.equalTo(_codeImageView.mas_right).offset(kRealValue(19));
        make.centerY.equalTo(_codeImageView);
        make.height.equalTo(_phoneTextField);
    }];
    [_codeLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.height.equalTo(_phoneLineView);
        make.top.equalTo(_codeImageView.mas_bottom).offset(kRealValue(21));
    }];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_whiteBackgroundView.mas_bottom).offset(- kRealValue(50));
        make.left.equalTo(_whiteBackgroundView).offset(kRealValue(47));
        make.right.equalTo(_whiteBackgroundView).offset(- kRealValue(47));
        make.height.offset(kRealValue(44));
    }];
}

#pragma mark - 懒加载
- (UIImageView *)backgroudImageView{
    if (!_backgroudImageView) {
        _backgroudImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_login_header"]];
    }
    return _backgroudImageView;
}

- (UIView *)whiteBackgroundView{
    if (!_whiteBackgroundView) {
        _whiteBackgroundView = [[UIView alloc]init];
        _whiteBackgroundView.backgroundColor = [UIColor QSColorWhiteFFFFFF];
        _whiteBackgroundView.layer.cornerRadius = 13;
//        _whiteBackgroundView.layer.shadowOffset = CGSizeMake(0, 5);
//        _whiteBackgroundView.layer.shadowColor = [UIColor colorWithHexString:@"#128BEC"].CGColor;
//        _whiteBackgroundView.layer.shadowOpacity = 0.5f;
//        _whiteBackgroundView.layer.shadowRadius = 5;
//        _whiteBackgroundView.layer.masksToBounds = NO;
        
        _whiteBackgroundView.layer.masksToBounds = NO;
        _whiteBackgroundView.layer.shadowColor = [UIColor QSColorGrayA1A1A1].CGColor;
        _whiteBackgroundView.layer.shadowOffset = CGSizeMake(0, 0);
        _whiteBackgroundView.layer.shadowOpacity = 0.2f;
        _whiteBackgroundView.layer.shadowRadius = 10;
        
    }
    return _whiteBackgroundView;
}

- (UIImageView *)titleBackgroundImageView{
    if (!_titleBackgroundImageView) {
        _titleBackgroundImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_login_title"]];
    }
    return _titleBackgroundImageView;
}

- (UIImageView *)phoneImageView{
    if (!_phoneImageView) {
        _phoneImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_login_phone"]];
    }
    return _phoneImageView;
}

-(UITextField *)phoneTextField{
    if (!_phoneTextField) {
        _phoneTextField = [[UITextField alloc]init];
        NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:kLastUserPhone];
        if (phone.length > 0) {
            _phoneTextField.text = phone;
        }
        _phoneTextField.placeholder = @"请输入您的手机号码";
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.delegate = self;
    }
    return _phoneTextField;
}

- (UIView *)phoneLineView{
    if (!_phoneLineView) {
        _phoneLineView = [[UIView alloc]init];
        _phoneLineView.backgroundColor = [UIColor QSColorGrayDDDDDD];
    }
    return _phoneLineView;
}

- (UIImageView *)codeImageView{
    if (!_codeImageView) {
        _codeImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_login_password"]];
    }
    return _codeImageView;
}

-(UITextField *)codeTextField{
    if (!_codeTextField) {
        _codeTextField = [[UITextField alloc]init];
        _codeTextField.placeholder = @"请输入验证码";
        _codeTextField.keyboardType = UIKeyboardTypeNumberPad;
        _codeTextField.delegate = self;

    }
    return _codeTextField;
}

- (UIView *)codeLineView{
    if (!_codeLineView) {
        _codeLineView = [[UIView alloc]init];
        _codeLineView.backgroundColor = [UIColor QSColorGrayDDDDDD];
    }
    return _codeLineView;
}

- (JKCountDownButton *)sendCodeButton{
    if (!_sendCodeButton) {
        _sendCodeButton = [JKCountDownButton buttonWithType:UIButtonTypeCustom];
        [_sendCodeButton setTitle:@"获取" forState:UIControlStateNormal];
        [_sendCodeButton setTitleColor:[UIColor QSColorWhiteFFFFFF] forState:UIControlStateNormal];
        [_sendCodeButton setTitleColor:[UIColor QSColorGrayC1C1C1] forState:UIControlStateDisabled];
        _sendCodeButton.titleLabel.font = [UIFont QSFontOfSize14];
        _sendCodeButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
        _sendCodeButton.layer.cornerRadius = 2;
        _sendCodeButton.layer.masksToBounds = YES;

        [_sendCodeButton addTarget:self action:@selector(sendCodeAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendCodeButton;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor QSColorWhiteFFFFFF] forState:UIControlStateNormal];
        _loginButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
        _loginButton.layer.cornerRadius = 22;
        [_loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (void)sendCodeAction:(JKCountDownButton *)sender{
    if (!_phoneTextField.text.length) {
        [MBProgressHUD showText:@"请填写手机号"];
        return;
    }
    if (![_phoneTextField.text checkTelNumber]) {
        [MBProgressHUD showText:@"填写手机格式不正确"];
        return;
    }
    //先验证号码是否存在于服务器
    [QSUserInterface checkPhoneWithPhone:_phoneTextField.text andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            if ([result[@"phoneCheck"] integerValue] == 1) {
                NSLog(@"可以发送");
                [self sendCodeWithCodeButton:sender];//发送验证码
            }else{
                [QSAppKeyWindow showAutoHideHudWithText:@"此账号不存在！"];
                return;
            }
        }
    }];
}

- (void)sendCodeWithCodeButton:(JKCountDownButton *)sender{
    sender.enabled = NO;
    [sender startWithSecond:60];
    [QSUserInterface sendCodeWithPhone:_phoneTextField.text andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, NSDictionary * _Nonnull result) {
        if (rspStatusAndMessage.code == kResponseSuccessCode) {
            [QSAppKeyWindow showAutoHideHudWithText:@"验证码已发送"];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [sender didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
                    countDownButton.enabled = NO;
                    countDownButton.layer.borderColor = [UIColor QSColorGrayC1C1C1].CGColor;
                    countDownButton.backgroundColor = [UIColor lightGrayColor];
                    NSString *title = [NSString stringWithFormat:@"%ds",second];
                    return title;
                }];
                [sender didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
                    countDownButton.enabled = YES;
                    countDownButton.layer.borderColor = [UIColor QSColorBlue3F7DEF].CGColor;
                    countDownButton.backgroundColor = [UIColor colorWithHexString:@"#128BEC"];
                    return @"获取";
                }];
            }];
        }else{
            sender.enabled = YES;
        }
    }];
    DLog(@"发送验证码");
}

- (void)loginAction:(UIButton *)sender{
    if (!_phoneTextField.text.length) {
        [QSAppKeyWindow showAutoHideHudWithText:@"请输入手机号"];
        return;
    }
    if (![_phoneTextField.text checkTelNumber]) {
        [QSAppKeyWindow showAutoHideHudWithText:@"手机号格式不正确"];
        return;
    }
    if (!_codeTextField.text.length) {
        [QSAppKeyWindow showAutoHideHudWithText:@"验证码不能为空"];
        return;
    }
    [QSAppKeyWindow showIndeterminateHudWithText:@"正在登录..."];
   
    [[QSUserManager sharedQSUserManager] removeUser];
    [QSUserInterface userLoginWithphone:_phoneTextField.text phoneCode:_codeTextField.text andBlock:^(ResponseMessage * _Nonnull rspStatusAndMessage, QSUserModel * _Nonnull user) {
        if (rspStatusAndMessage.code == kResponseSuccessCode && user.allToken) {
            NSLog(@"登录信息%@", user.allToken);
            [QSAppKeyWindow showAutoHideHudWithText:@"登录成功"];
            user.isLogin = YES;
            [[QSUserManager sharedQSUserManager] saveUser:user];
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kLoginStateKey];
            [[NSUserDefaults standardUserDefaults] setObject:self.phoneTextField.text forKey:kLastUserPhone];
            [self turnToHomeViewController];
    
        }else{
            [QSAppKeyWindow showAutoHideHudWithText:rspStatusAndMessage.message];
        }
    }];
    
    
}

- (void)turnToHomeViewController {
    if ([[UIViewController currentViewController] isKindOfClass:NSClassFromString(@"QSMainTabBarController")]) {
        return;
    }
    CATransition * transition = [[CATransition alloc] init];
    transition.type = @"fade";
    transition.duration = 0.2;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:transition forKey:nil];
    [UIApplication sharedApplication].keyWindow.rootViewController = [[QSMainTabBarController alloc] init];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == _codeTextField) {
        if (string.length == 0) return YES;//允许删除。
        if (textField.text.length >= 6) {
            return NO;
        }else{
            return YES;
        }
    }else{
        if (string.length == 0) return YES;//允许删除。
        if (textField.text.length >= 11) {
            return NO;
        }else{
            return YES;
        }
    }
}
/**
*  键盘即将显示的时候调用
*/
- (void)keyboardWillShow:(NSNotification *)note{
    [self keyboardWillShow:note TextY:self.codeTextField.y];
}

/**
 *  键盘即将退出的时候调用
 */
- (void)keyboardWillHide:(NSNotification *)note{
    [self keyboardHiden:note];
}
- (void)dealloc{
    //移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


@end
